<?php 

/**
* 数据库操作类
*/
class Model
{
	public $table;//要操作表
	public static $db;//数据库链接对象
	public $errorInfo;//错误信息
	public $where;//where条件
	//构造函数实例化pod对象
	public function __construct($table="")
	{
		//把表名放属性上
		$this->table=$table;
		try {
			if(!self::$db){
				//实例化pdo对象
				self::$db = new PDO(C("DB_TYPE").":host=".C("DB_HOST").";dbname=".C("DB_NAME").";charset=utf8",C("DB_USERNAME"),C("DB_PASS")); 
			}
		} catch (PDOException  $e) {
			$this->errorInfo ="数据链接失败，失败原因：".$e;
		}
	}
	// 直接执行原生查询sql
	public function query($sql)
	{
		$res = self::$db->query($sql);

		if($res){
			return $res->fetchAll(PDO::FETCH_ASSOC);
		}else{
			$this->errorInfo = "查询失败：失败代码：".self::$db->errorCode()."错误原因：".self::$db->errorInfo()[2];
			return false;
		}
	}
	// 直接执行原生增删改sql
	public function exec($sql)
	{
		$res = self::$db->exec($sql);

		if($res){
			return true;
		}else{
			$this->errorInfo = "查询失败：失败代码：".self::$db->errorCode()."错误原因：".self::$db->errorInfo()[2];
			return false;
		}
	}
	//增加方面
	public function add($data)
	{	
		//组字段
		$keys = implode(",", array_keys($data));
		//组值
		$values = implode("','", $data);
		//组sql
		$sql = "insert into ".$this->table." (".$keys.") values('".$values."')";

		$res = $this->exec($sql);

		if($res){
			return self::$db->lastInsertId(); 
		}else{
			return false;
		}
	}
	//删除
	public function delete($id="")
	{
		if($id){
			$pkey = $this->getPkey();
			//组sql
			$sql = "delete from ".$this->table." where ".$pkey."=".$id;
		}else{
			//组sql
			$sql = "delete from ".$this->table.$this->where;
		}

		return $this->exec($sql);

	}
	//加where条件
	public function where($where)
	{
		$this->where = " where ".$where;
		return $this;
	}
	//更新 
	public function save($data)
	{

		$str = "";

		foreach ($data as $k => $v) {
			$str.=$k."='".$v."',";
		}

		$str = rtrim($str,',');

		$sql = "update ".$this->table." set ".$str." ".$this->where;

		return $this->exec($sql);

	}
	//获取主键
	public function getPkey()
	{
		$sql = "desc ".$this->table;

		$res = $this->query($sql);

		foreach ($res as  $v) {
			if($v['Key']=="PRI"){
				return $v["Field"];
			}
		}

	}
	//查找一条
	public function findOne($id="")
	{
		if($id){
			$pkey = $this->getPkey();
			$sql = "select * from ".$this->table." where ".$pkey."=".$id."limit 1";
		}else{
			$sql = "select * from ".$this->table.$this->where." limit 1";
		}
		
		return $this->query($sql);
	}
	//查找全部
	public function findAll()
	{
		$sql = "select * from ".$this->table.$this->where;
		return $this->query($sql);
	}
	//获取错误信息
	public function getError()
	{
		return $this->errorInfo;
	}
}












 ?>